package LeetCode;

public class LC_002_AddTwoNumbers {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {


    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //虚拟节点
        ListNode dummyHead = new ListNode(0);
        //三个指针
        ListNode p = l1, q = l2, curr = dummyHead;
        //进位
        int carry = 0;
        //循环，不包含最后一位
        while (p != null || q != null) {
            //取值
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            //求和
            int sum = carry + x + y;
            //求进位
            carry = sum / 10;
            //求末位，创建新节点加入新的链表
            curr.next = new ListNode(sum % 10);
            //指针移动
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        //最后一位有进位则加上进位的新节点
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        //虚拟节点的下一个元素
        return dummyHead.next;
    }
}
